import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:home_framework/models/contactor_entity.dart';
import 'package:home_framework/routers/fluro_router.dart';
import 'package:home_framework/view_models/message/contactor_list_model.dart';
import 'package:provider/provider.dart';

class MessagePage extends StatelessWidget {
  const MessagePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => ContactorListModel(),
      child: _ContactorPage(),
    );
  }
}

class _ContactorPage extends StatelessWidget {
  _ContactorPage({Key? key}) : super(key: key);

  final EasyRefreshController _refreshController = EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    List<ContactorEntity> contactors =
        context.watch<ContactorListModel>().contactors;
    return Scaffold(
      appBar: AppBar(
        title: Text('聊天', style: Theme.of(context).textTheme.headline4),
        brightness: Brightness.dark,
      ),
      body: EasyRefresh(
        controller: _refreshController,
        firstRefresh: true,
        onRefresh: () async {
          context.read<ContactorListModel>().refresh();
        },
        onLoad: () async {
          context.read<ContactorListModel>().load();
        },
        child: ListView.builder(
          itemBuilder: (context, index) {
            return ListTile(
              leading: _getRoundImage(contactors[index].avatar, 50),
              title: Text(contactors[index].nickname),
              subtitle: Text(
                contactors[index].description,
                style: TextStyle(fontSize: 14.0, color: Colors.grey),
              ),
              onTap: () {
                debugPrint(contactors[index].id);
                RouterManager.router.navigateTo(context,
                    '${RouterManager.chatPath}?toUserId=${contactors[index].id}');
              },
            );
          },
          itemCount: contactors.length,
        ),
      ),
    );
  }

  Widget _getRoundImage(String imageUrl, double size) {
    return Container(
      width: size,
      height: size,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(size / 2)),
      ),
      child: CachedNetworkImage(
        imageUrl: imageUrl,
      ),
    );
  }
}
